"""This module provides mydouyn"""

import datetime
import json
import logging
import os
import platform
import random
import time

from playwright.sync_api import Page, sync_playwright


# from pythonTryEverything.putdonwphone.data import englisword
# from putdonwphone.data import englisword
class CMyRedBook:
    """
    This class represents a GetupHabit.

    Parameters:
    - save_picture_path (str): The path to save pictures.
    - default_picture_path (str): The default path for pictures.
    """

    def __init__(
        self,
        cookies_path: str,
        login_url: str,
        upload_picture_url: str,
        upload_mp4_url: str,
    ):
        self.cookies_path = cookies_path
        self.login_url = login_url
        self.upload_picture_url = upload_picture_url
        self.upload_mp4_url = upload_mp4_url
        # playwright 部分
        self.browser = None
        self.page = None
        print("create CMyRedBook")

    def __del__(self):
        print("CMyRedBook is being destroyed")

    def upload_picture(self, picture_path: str, habit_name: str, habit_detail: str):
        """
        upload_picture
        """
        with sync_playwright() as playwright:
            display_headless = False
            # display_headless = True
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            if sys == "Linux":
                self.browser = playwright.chromium.launch(headless=display_headless)
            else:
                self.browser = playwright.chromium.launch(
                    channel="chrome", headless=display_headless
                )
            login_page = self.login_or_restore_cookies()
            self.msg_up_load(login_page, picture_path, habit_name, habit_detail)
            self.browser.close()

    def login_or_restore_cookies(self) -> Page:
        """
        登录
        """
        user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.6045.21 Safari/537.36"
        sys = platform.system()
        if sys == "Linux":
            user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"

        context = self.browser.new_context(user_agent=user_agent)
        context.clear_cookies()
        page = context.new_page()
        page.goto(self.login_url)

        if os.path.exists(self.cookies_path):
            print("load cookies--------------------")
            # 从文件中加载 cookies
            with open(self.cookies_path, "r", encoding="utf-8") as f:
                cookies = json.load(f)
            context.add_cookies(cookies)
            time.sleep(3)
        else:
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            # 扫名二维码登录 需要人工处理
            print("扫名二维码登录 需要人工处理--------------------")
            time.sleep(120)
            cookies = page.context.cookies()
            with open(self.cookies_path, "w", encoding="utf-8") as f:
                f.write(json.dumps(cookies))
        print("login_or_restore_cookies")
        return page

    def tell_good(self, habit_name: str, habit_detail: str):
        """
        upload_picture
        """
        # with sync_playwright() as playwright:
        #     self.browser = playwright.chromium.launch(headless=False)
        #     login_page = self.login_or_restore_cookies()
        #     self.tell_good_maimai(login_page, habit_name, habit_detail)
        #     self.browser.close()
        with sync_playwright() as playwright:
            display_headless = False
            sys = platform.system()
            if sys == "Linux":
                display_headless = True
            self.browser = playwright.chromium.launch(
                channel="chrome", headless=display_headless
            )
            login_page = self.login_or_restore_cookies()
            self.tell_good_leetcode(login_page, habit_name, habit_detail)
            self.browser.close()

    def tell_good_leetcode(self, page: Page, habit_name: str, habit_detail: str):
        """
        发布笔记
        """
        page.goto(self.upload_picture_url)
        page.wait_for_timeout(6 * 1000)
        print(f"open  {self.upload_picture_url}")
        page_count = page.locator(".flex.items-start.justify-between.gap-4")
        print(page_count.count())
        for i in range(5, page_count.count()):
            try:
                page.mouse.down()
                page.mouse.down()
                page.mouse.down()
                if i > 50:
                    break
                page.wait_for_timeout(1 * 1000)
                print(f"{i} + {page_count.nth(i)}")
                page_count.nth(i).click()
                page.wait_for_timeout(4 * 1000)
                now = datetime.datetime.now()
                # 将 datetime 对象格式化为 "YYYY-MM-DD HH:MM:SS"
                formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
                temp = habit_detail + "\n" + formatted_time
                page.get_by_role("textbox", name="请输入评论").click()
                page.wait_for_timeout(1 * 1000)
                page.get_by_role("textbox", name="请输入评论").fill(temp)
                page.wait_for_timeout(1 * 1000)

                page.get_by_role("button", name="评论").click()
<<<<<<< HEAD
                num = random.randint(0, 60)
=======
                num = random.randint(0, 20)
>>>>>>> a5a4259ee1064783c2d84128a3493d731c943d01
                page.wait_for_timeout(num * 1000)
                page.goto("https://leetcode.cn/discuss/")
                # https://leetcode.cn/discuss/post/3676518/mei-tuan-yi-mian-513dian-hua-oc-by-jia-s-m5rd/

            except Exception as myunkonw:
                print(f"发生异常：{myunkonw}")
        # 控制发文的次数
        # begin = 4
        # end = 10
        # step = 5
        # # 点击点赞100次
        # for i in range(begin, end):
        #     try:
        #         for j in range(0, 10):
        #             page.mouse.down()
        #             page.mouse.down()
        #             page.mouse.down()
        #             page.mouse.down()
        #             page.wait_for_timeout(1000)
        #         num = random.randint(0, 30)
        #         page.wait_for_timeout(num * 1000)
        #         print(f"click {i}")

        #         # open
        #         with page.expect_popup(timeout=10 * 1000) as jump_page_info:
        #             page.locator(
        #                 f"div:nth-child({i}) > div:nth-child(4) > div:nth-child(2) > .sc-CtfFt > .sc-laTMn"
        #             ).click()

        #         msg_page = jump_page_info.value
        #         num = random.randint(0, 5)
        #         msg_page.wait_for_timeout(num * 1000)
        #         msg_page.locator(".inputPanel").click()
        #         msg_page.wait_for_timeout(1 * 1000)
        #         # 获取当前本地时间（包含日期和时间）
        #         now = datetime.datetime.now()
        #         # 将 datetime 对象格式化为 "YYYY-MM-DD HH:MM:SS"
        #         formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
        #         temp = habit_detail + "\n" + formatted_time
        #         msg_page.locator(".inputPanel").fill(temp)
        #         msg_page.wait_for_timeout(1 * 1000)
        #         msg_page.get_by_text("发布", exact=True).click()
        #         num = random.randint(0, 30)
        #         msg_page.wait_for_timeout(num * 1000)
        #         # https://playwright.dev/python/docs/api/class-page#page-close
        #         msg_page.close()
        #         time.sleep(1)
        #     except Exception as myunkonw:
        #         print(f"发生异常：{myunkonw}")

        #     print(f"item {i} done")


####################################
def interface_auo_tell_good_leetcode(artile_title, artile_content):
    """
    对外调用接口
    """
    sys = platform.system()
    login_url = "https://leetcode.cn/accounts/login"
    upload_picture_url = "https://leetcode.cn/discuss/"
    upload_mp4_url = "https://leetcode.cn/discuss/"
    sys = platform.system()
    if sys == "Windows":
        cookies_path = r"D:\mp4\etc\leetcode_small.json"
    elif sys == "Darwin":
        cookies_path = r"/Users/wangchuanyi/mp4/etc/leetcode_small.json"
    else:
        cookies_path = r"/root/bin/leetcode_small.json"

    autoupload = CMyRedBook(cookies_path, login_url, upload_picture_url, upload_mp4_url)

    try:
        autoupload.tell_good(artile_title, artile_content)
    except Exception as err:
        print(f"Unexpected {err=}, {type(err)=}")
    finally:
        print("...")


if __name__ == "__main__":
    # 获取内容
    local_file_path = (
        r"/Users/wangchuanyi/money/years/p1_good_night/auto/good/etc/config.txt"
    )
    sys = platform.system()
    if sys == "Windows":
        local_file_path = r"D:\p1_good_night\auto\good\etc\config.txt"
    f = open(local_file_path, encoding="utf-8")
    artile_content = f.read()
    print(artile_content)
    f.close()

    artile_title = "学会销售自己的产品"

    interface_auo_tell_good_leetcode(artile_title, artile_content)

## playwright codegen https://leetcode.cn/discuss/
